<?php

namespace App\Http\Controllers\Api;

use App\Address;
use App\Http\Controllers\ApiResponse;
use App\Http\Controllers\Controller;
use App\Http\Requests\AddressStoreRequest;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class AddressController extends Controller
{
    use ApiResponse;
    public $uid;
    public function __construct()
    {
        $this->uid=auth('api')->id();
    }

    /**
     * @return \Illuminate\Http\JsonResponse
     */
    public function index()
    {
        $data = Address::where('uid', $this->uid)->orderByDesc('default')->get();
        return $this->data($data);
    }

    /**
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function store(AddressStoreRequest $request)
    {
        $find = Address::where('uid', $this->uid)->first();
        if (!$find) {
            $request->merge(['uid' => $this->uid, 'default' => 1]);
        } else {
            $request->merge(['uid' => $this->uid]);
        }
        if ($request->get('default') == 1) {
            Address::where('uid', $this->uid)->update(['default' => 0]);
        }
        $created = Address::create($request->all());
        if ($created) {
            return $this->message_success("添加成功");
        } else {
            return $this->message_error("添加失败");
        }
    }

    /**
     * @param $id
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function update($id, Request $request)
    {
        DB::beginTransaction();
        try {
            if ($request->get('default') == 1) {
                Address::where('uid', $this->uid)->update(['default' => 0]);
            }
            $update = Address::where('id', $id)->update($request->all());
            DB::commit();
            return $this->message_success("修改成功");

        } catch (\Exception $exception) {
            DB::rollBack();
            Log::error("地址修改失败:",[$request->all(),$this->uid,$exception->getMessage()]);
            return $this->message_error("修改失败");
        }
    }

    /**
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function destroy($id)
    {
        Address::where('id', $id)->delete();

        return $this->message_success("删除成功");
    }

    public function get_default()
    {
        $result=Address::where('uid',$this->uid)->where('default',1)->first();
        return $this->data($result);
    }

}
